package com.hsg.lsn13.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.hsg.lsn13.ac.KeepActivity;
import com.hsg.lsn13.ac.MainActivity;
import com.hsg.lsn13.receiver.KeepReceiver;

import java.lang.ref.WeakReference;

public class KeepManager {

    public static final KeepManager ourInstance=new KeepManager();
    private KeepReceiver keepReceiver;
    private WeakReference<Activity> mKeepAct;

    public static KeepManager getOurInstance(){
        return ourInstance;
    }

    public void registerKeep(Context context){
        IntentFilter filter=new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        keepReceiver=new KeepReceiver();
        context.registerReceiver(keepReceiver,filter);
    }

    public void startKeep(Context context) {
        Intent intent=new Intent(context, KeepActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public void setKeep(KeepActivity keep) {
        mKeepAct = new WeakReference<Activity>(keep);
    }

    public void finishKeep(Context context) {
        if(null!=mKeepAct){
            Activity activity = mKeepAct.get();
            if(null!=activity){
                activity.finish();
            }
            mKeepAct = null;
        }
    }

    public void unregisterKeep(Context context) {
        if(null!=keepReceiver){
            context.unregisterReceiver(keepReceiver);
        }
    }
}
